package com.hongdee.crm.task.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.Constant;
import com.hongdee.crm.base.service.ICarZhService;
import com.hongdee.crm.car.service.ITCrmCarService;
import com.hongdee.crm.task.dao.ITCrmCarMaintainTaskDao;
import com.hongdee.crm.task.dao.ITCrmTaskDao;
import com.hongdee.crm.task.dao.ITCrmTaskManageDao;
import com.hongdee.crm.task.entity.TCrmTask;
import com.hongdee.crm.task.entity.TCrmTaskCarVin;
import com.hongdee.crm.task.entity.TCrmTaskCarVinDetail;
import com.hongdee.crm.task.entity.TCrmTaskReal;
import com.hongdee.crm.task.service.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by My on 2017/4/28.
 */
@Service
public class TCrmTaskManageServiceImpl implements ITCrmTaskManageService {

    @Autowired
    private ITCrmTaskDao taskDao;

    @Autowired
    private ITCrmTaskManageDao manageDao;

    @Autowired
    private ICarZhService carZhService;

    @Autowired
    private ITCrmCarMaintainTaskDao crmCarMaintainTaskDao;

    @Autowired
    private ITCrmCarWorkorderTaskService crmCarWorkorderTaskService;
    @Autowired
    private ITCrmCarMaintainMileTaskService crmCarMaintainMileTaskService;
    @Autowired
    private ITCrmTimeTaskService crmTimeTaskService;
    /*新车首月*/
    @Resource(name = "FirstMonthMaintainTaskService")
    private ITCrmCarMaintainTaskService firstMonthMaintainTaskService;

    /* 基盘 车辆行驶里程 */
    @Autowired
    private ICarBaseCountService carBaseCountService;

    private final Integer LIMIT = 1000;

    @Autowired
    private ITCrmCarService crmCarService;

    @Override
    public void parseExcel(MultipartFile file, String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        TCrmTaskCarVin taskCarVin = this.createCrmTaskCarVin(file, uid, companyId);
        String fileName = file.getOriginalFilename();
        String type = fileName.substring(fileName.lastIndexOf("."));
        if (type != null && (type.endsWith("xlsx") || type.endsWith("xls"))) {
            taskCarVin = (TCrmTaskCarVin) taskDao.saveOrUpdate(taskCarVin);
            List<TCrmTaskCarVinDetail> carVinDetails = this.readExcel(file, companyId, uid, taskCarVin.getId());
            taskDao.saveOrUpdateList(carVinDetails);
        } else {
            throw new Exception("无法识别的文件格式！");
        }
    }

    @Override
    public List<TCrmTaskCarVin> vinFileLists(String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        List<Map<String, Object>> list = manageDao.getVinFileLists(uid, companyId);
        List<TCrmTaskCarVin> tCrmTaskCarVins = new ArrayList<>();
        for (Map<String, Object> map : list) {
            TCrmTaskCarVin taskCarVin = new TCrmTaskCarVin();
            taskCarVin.setId(String.valueOf(map.get("id")));
            String fileName = String.valueOf(map.get("file_name"));
            Long createTime = Long.valueOf(String.valueOf(map.get("create_time")));
            if (createTime != null) {
                String time = DateUtils.formatLongTime(createTime, "yyyyMMddHHmmss");
                fileName = time + "_" + fileName;
            }
            taskCarVin.setFileName(fileName);
            tCrmTaskCarVins.add(taskCarVin);
        }
        return tCrmTaskCarVins;
    }

    private TCrmTaskCarVin createCrmTaskCarVin(MultipartFile file, String uid, String companyId) {
        //获取文件名
        String fileName = file.getOriginalFilename();
        TCrmTaskCarVin taskCarVin = new TCrmTaskCarVin();
        taskCarVin.setCompanyId(companyId);
        taskCarVin.setuId(uid);
        taskCarVin.setCreateTime(new Date().getTime());
        taskCarVin.setFileName(fileName);
        return taskCarVin;
    }

    /**
     * 读取xls文件内容
     *
     * @return List<XlsDto>对象
     * @throws IOException 输入/输出(i/o)异常
     */
    private List<TCrmTaskCarVinDetail> readExcel(MultipartFile file, String companyId, String uid, String carVinId) throws IOException {
        InputStream is = file.getInputStream();
        Workbook book = null;
        try {
            book = new XSSFWorkbook(is);
        } catch (Exception ex) {
            book = new HSSFWorkbook(is);
        }
        List<TCrmTaskCarVinDetail> list = new ArrayList<TCrmTaskCarVinDetail>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet < book.getNumberOfSheets(); numSheet++) {
            Sheet sheet = book.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) {
                    continue;
                }
                TCrmTaskCarVinDetail carVinDetail = new TCrmTaskCarVinDetail();
                // 循环列Cell
                Cell xh = row.getCell(0);
                if (xh == null) {
                    continue;
                }
                String vin=getValue(xh);
                if("".equals(vin)){
                    continue;
                }
                carVinDetail.setVin(vin);
                carVinDetail.setCompanyId(companyId);
                carVinDetail.setuId(uid);
                carVinDetail.setCarVinId(carVinId);
                carVinDetail.setCreateTime(new Date().getTime());
                carVinDetail.setCreateUser(uid);
                list.add(carVinDetail);
            }
        }
        return list;
    }

    /**
     * 得到Excel表中的值
     *
     * @param cell Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private String getValue(Cell cell) {
        if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(cell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(cell.getStringCellValue());
        }
    }

    /**
     * 组织查询根据选择的车辆或者查询条件生成指定类型的任务
     *
     * @param params
     * @param uid
     * @param pcode
     * @param code
     * @param expectDate
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Integer createCarZhToTask(Map params, String uid, String pcode, String code, String expectDate, List<Map> data,String title) throws Exception {
        Integer nums = 0;
        if (data.size() > 0) {
            nums = this.createParamsCarsToTask(params, uid, pcode, code, expectDate, data,title);
        } else {
            nums = this.createParamsCarToTask(params, uid, pcode, code, expectDate,title);
        }
        return nums;
    }


    /**
     * 根据条件将查询到的车辆生成指定类型的任务
     *
     * @param params
     * @param uid
     * @param pcode
     * @param code
     * @param expectDate
     * @return
     * @throws Exception
     */
    public Integer createParamsCarToTask(Map params, String uid, String pcode, String code, String expectDate, String title) throws Exception {
        Integer nums = 0;
        int start = 0;
        String companyId = TokenUtil.getCompanyId(uid);
        while (true) {
            Map map = carZhService.page(String.valueOf(start * LIMIT), String.valueOf(LIMIT), params, uid);
            List<Map<String, Object>> list = (ArrayList) map.get("dataList");
            if (list.size() == 0) {
                start = 0;
                break;
            }
            List<TCrmTask> taskList = new ArrayList<>();
            for (Map<String, Object> carMap : list) {
                TCrmTask tCrmTask = this.getCrmTask(carMap, pcode, code, expectDate, companyId, uid, title);
                taskList.add(tCrmTask);
            }
            if (taskList.size() > 0) {
                int num = taskList.size();
                crmCarMaintainTaskDao.insertMaintailLists(taskList);
                nums += num;
            }
            start++;
        }
        return nums;
    }

    /**
     * 将指定的车辆信息生成指定类型的任务
     *
     * @param params
     * @param uid
     * @param pcode
     * @param code
     * @param expectDate
     * @param data
     * @return
     * @throws Exception
     */
    public Integer createParamsCarsToTask(Map params, String uid, String pcode, String code, String expectDate, List<Map> data, String title) throws Exception {
        Integer nums = 0;
        Map map = carZhService.page("", "", params, uid, data);
        String companyId = TokenUtil.getCompanyId(uid);
        List<Map<String, Object>> list = (ArrayList) map.get("dataList");
        if (list.size() > 0) {
            List<TCrmTask> taskList = new ArrayList<>();
            for (Map<String, Object> carMap : list) {
                TCrmTask tCrmTask = this.getCrmTask(carMap, pcode, code, expectDate, companyId, uid, title);
                taskList.add(tCrmTask);
            }
            if (taskList.size() > 0) {
                int num = taskList.size();
                crmCarMaintainTaskDao.insertMaintailLists(taskList);
                nums += num;
            }
        }
        return nums;

    }

    /**
     * 生成任务实体
     *
     * @param carMap
     * @param pcode
     * @param code
     * @param expectDate
     * @param companyId
     * @param uid
     * @return
     */
    public TCrmTask getCrmTask(Map carMap, String pcode, String code, String expectDate, String companyId, String uid, String title) {
        TCrmTask task = new TCrmTask();
        String remindStr = "";
        String plateNum = String.valueOf(carMap.get("plateNum"));
        String uname = String.valueOf(carMap.get("ownerName"));
        switch (pcode) {
            case "ga":
                remindStr = this.getTsTextByCode(code);
                break;
            case "bx":
                remindStr = this.getTsTextByCode(code);
                break;
            case "by":
                remindStr = this.getTsTextByCode(code);
                break;
            case "ls":
                remindStr = this.getTsTextByCode(code);
                break;
            case "qt":
                remindStr = this.getTsTextByCode(code);
                remindStr = remindStr + "，" + title;
                break;
        }
        remindStr = String.format(remindStr, plateNum, uname);
        task.setVIN(carMap.get("vin").toString());
        task.setCarId(carMap.get("carId").toString());
        task.setPlateNum(plateNum);
        task.setCompanyId(companyId);
        task.setLinkman(uname);
        if (carMap.get("contactPhone") != null) {
            task.setLinkphone(carMap.get("contactPhone").toString());
        }
        task.setExpectDate(expectDate);
        task.setStatus("0");
        task.setIsBack("0");
        task.setTypePCode(pcode);
        task.setTypeCode(code);
//        task.setSaId(uid);
        task.setContent(remindStr);
        return task;
    }

    /**
     * 根据任务类型获得提示内容
     *
     * @param code
     * @return
     */
    public String getTsTextByCode(String code) {
        String tx = "";
        switch (code) {
            case "sr":
//                tx="[%s]的车主[%s]将于%s过生日";
                tx = "[%s]的车主[%s]生日提醒";
                break;
            case "zbt":
//                tx="%s的车，车主[%s],%s质保日，[质保时间]%s";
                tx = "%s的车，车主[%s]质保提醒";
                break;
            case "ybt":
//                tx="%s的车主[%s]将于%s延保到期";
                tx = "%s的车主[%s]延保到期提醒";
                break;
            case "ns":
//                tx="%s的车,车主[%s]，将于%s进行年审";
                tx = "%s的车,车主[%s]，年审提醒";
                break;
            case "6":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "7":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "8":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "9":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "10":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "11":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "12":
//                tx="%s 的车，车主[%s]将于[%s]起，超过%d个月，处于准流失状态";
                tx = "%s 的车，车主[%s]超过%d个月，处于准流失状态";
                break;
            case "cnj":
//                tx="%s的车主[%s]将于%s交强险到期";
                tx = "%s的车主[%s]交强险到期提醒";
                break;
            case "cns":
//                tx="%s的车主[%s]将于%s商业险到期";
                tx = "%s的车主[%s]商业险到期提醒";
                break;
            case "xbs":
//                tx="%s的车主[%s]将于%s商业险到期";
                tx = "%s的车主[%s]商业险到期提醒";
                break;
            case "xnj":
//                tx="%s的车主[%s]将于%s交强险到期";
                tx = "%s的车主[%s]交强险到期提醒";
                break;
            case "jds":
//                tx="%s的车主[%s]将于%s商业险到期";
                tx = "%s的车主[%s]商业险到期提醒";
                break;
            case "jdj":
//                tx="%s的车主[%s]将于%s交强险到期";
                tx = "%s的车主[%s]交强险到期提醒";
                break;
            case "hyt":
//                tx="%s的车主[%s]%s挂牌，保险活跃用户";
                tx = "%s的车主[%s]挂牌，保险活跃用户";
                break;
            case "fhyt":
//                tx="%s的车主[%s]%s挂牌，保险非活跃用户";
                tx = "%s的车主[%s]挂牌，保险非活跃用户";
                break;
            case "sb_mby":
                tx = "%s的车，车主%s,首保提醒.[目标月]";
                break;
            case "sb_mbr":
                tx = "%s的车，车主%s,首保提醒";
                break;
            case "eb_mby":
                tx = "%s的车，车主%s,二保提醒.[目标月]";
                break;
            case "eb_mbr":
                tx = "%s的车，车主%s,二保提醒";
                break;
            case "db_mby":
                tx = "%s的车，车主%s,常保提醒.[目标月]";
                break;
            case "db_mbr":
                tx = "%s的车，车主%s,常保提醒";
                break;
            case "sy_mbr":
                tx = "%s的车，车主%s,新车首月提醒";
                break;
            case "zdy":
                tx = "%s的车，车主%s";
                break;
        }
        return tx;
    }

    /**
     * 根据保养计算器生成相应的定保、首保任务，并保存其相应信息
     *
     * @param uid
     * @param paramMap
     * @return
     */
    @Override
    public TCrmTaskReal saveCarSbAndDbTask(String uid, Map<String, Object> paramMap) throws Exception {
        String taskType = StringUtil.formatNull(paramMap.get("typeCode"));
        if (taskType == null) {
            throw new Exception("未知的任务类型");
        }
        TCrmTaskReal task = null;
        taskType = taskType.substring(0, 2);
        if ("sb".equals(taskType) || "sy".equals(taskType)) {
            task = this.caeateSbTaskInfo(paramMap, uid, taskType, true);
        }
        if ("db".equals(taskType) || "eb".equals(taskType)) {
            task = this.caeateDbTaskInfo(paramMap, uid, taskType, true);
        }
        //判断任务是否已经存在，如果存在则不在保存生成
        boolean flag = taskDao.checkLsTask(TokenUtil.getCompanyId(uid), StringUtil.formatNull(paramMap.get("carId")), task.getTypeCode(), task.getTypePCode());
        if (!flag) {//"expectDate" -> "2017-08-02"
            String updSql = "update t_crm_task_real set `status`='2' where type_code like ? and vin=? and company_id=? " +
                    "and DATE_FORMAT(expect_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m')";
            this.taskDao.executeSQL(updSql, taskType + "%", task.getVIN(), task.getCompanyId());
            this.taskDao.saveOrUpdate(task);
        }
        return task;
    }

    /**
     * 根据保养计算器生成相应的定保、首保任务
     *
     * @param uid
     * @param paramMap
     * @return
     */
    @Override
    public TCrmTaskReal createCarSbAndDbTask(String uid, Map<String, Object> paramMap) throws Exception {
        String taskType = StringUtil.formatNull(paramMap.get("typeCode"));
        if (taskType == null) {
            throw new Exception("未知的任务类型");
        }
        if(taskType.length()>1) {
            taskType = taskType.substring(0, 2);
            TCrmTaskReal task = null;
            if ("sb".equals(taskType) || "sy".equals(taskType)) {
                task = this.caeateSbTaskInfo(paramMap, uid, taskType, false);
            }
            if ("db".equals(taskType) || "eb".equals(taskType)) {
                task = this.caeateDbTaskInfo(paramMap, uid, taskType, false);
            }
            return task;
        }
        return null;
    }

    /**
     * 首保任务生成
     *
     * @param paramMap
     * @param uid
     * @return
     * @throws Exception
     */
    private TCrmTaskReal caeateSbTaskInfo(Map<String, Object> paramMap, String uid, String taskType, boolean flag) throws Exception {
        //获得车辆信息
        String sql="select id as carId,plate_num,owner_name,owner_tel,owner_phone,buy_date from t_crm_car where vin=? and company_id=?";
        List<String> ps=new ArrayList<>();
        ps.add(StringUtil.formatEmpty(paramMap.get("vin")));
        ps.add(TokenUtil.getCompanyId(uid));
        Map infoCarMap=this.manageDao.info(sql,ps.toArray());
        if(infoCarMap.size()==0){
            throw new Exception("未查找到车辆信息!!");
        }
        String code = "sb_mbr";
        Map<String, Object> map = (Map<String, Object>) paramMap.get("dbresp");
        paramMap.remove("dbresp");
        paramMap.putAll(map);
        if("".equals(StringUtil.formatEmpty(paramMap.get("nowMile")))){
            throw new Exception("请输入当前里程!!");
        }
        Float nowMile = Float.valueOf(String.valueOf(paramMap.get("nowMile")));
        Long buyDate = Long.valueOf(String.valueOf(infoCarMap.get("buyDate")));
        Long sixMonthDate = DateUtils.addMonthLongTime(buyDate, +6);
        Long nowDate = DateUtils.getNowTime();
        Float maintainMile = Float.valueOf(String.valueOf(paramMap.get("maintainMile")));
//      算法：（5000 - 当前里程）/ (当前里程 /（当前日期-销售日期）) +当前日期
        //当前日期 -销售日期
        Integer days = DateUtils.dateDifference(nowDate, buyDate);
        //剩余里程5000 - 当前里程
        Float surplusMile = maintainMile - nowMile;
        Long nextMaintainTime = 0L;
        if (surplusMile <= 0) {
//            throw new Exception("里程信息有误!!");
            nextMaintainTime = nowDate;
        } else {
            //平均里程
            Float avgMile = nowMile / days;
            //剩下里程除去平均里程 需要用多久跑完
            Float surplusHours = (surplusMile / avgMile) * 24;
            nextMaintainTime = DateUtils.addHourLongTime(nowDate, +surplusHours.intValue());
        }
        String tpl = "%s车，车主[%s],首保提醒!保修开始时间%s.";
        if (nextMaintainTime > sixMonthDate || nextMaintainTime < nowDate) {
            nextMaintainTime = sixMonthDate;
            code = "sb_mby";
            tpl += "[目标月]";
        }

        infoCarMap.putAll(paramMap);
        String plateNum = "";
        if (infoCarMap.get("plateNum") == null) {
            String vin = String.valueOf(infoCarMap.get("vin"));
            plateNum = vin.substring(vin.length() - 6, vin.length());
            infoCarMap.put("plateNum", plateNum);
        }
        tpl = String.format(tpl, plateNum, StringUtil.formatNull(infoCarMap.get("ownerName")),
                DateUtils.formatLongTimeByYYYYMMDD(buyDate));

        return this.saveTask(infoCarMap, nextMaintainTime, tpl, code, uid, flag);
    }

    /**
     * 定保任务生成
     *
     * @param paramMap
     * @param uid
     * @return
     * @throws Exception
     */
    private TCrmTaskReal caeateDbTaskInfo(Map<String, Object> paramMap, String uid, String taskType, boolean flag) throws Exception {
        String code = "db_mbr";
        Map<String, Object> map = (Map<String, Object>) paramMap.get("dbresp");
        paramMap.remove("dbresp");
        paramMap.putAll(map);
        Long nowDate = DateUtils.getNowTime();//当前时间
        if("".equals(StringUtil.formatEmpty(paramMap.get("nowMile")))){
            throw new Exception("请输入当前里程!!");
        }
        Float nowMile = Float.valueOf(String.valueOf(paramMap.get("nowMile")));//当前里程
        Long balanceDate = null;
        if(paramMap.get("balanceDate")!=null) {
            balanceDate=Long.valueOf(String.valueOf(paramMap.get("balanceDate")));//上次保养时间
        }else{
            balanceDate=DateUtils.addMonthLongTime(nowDate,-6);
        }
        Long sixMonthDate = DateUtils.addMonthLongTime(balanceDate, +6);

//        Long buyDate = Long.valueOf(String.valueOf(paramMap.get("buyDate")));
        Float runMile = Float.valueOf(String.valueOf(paramMap.get("runMile")));//上次保养里程
        Float maintainMile = Float.valueOf(String.valueOf(paramMap.get("maintainMile")));//保养间隔
//      算法：(保养间隔里程)/ ((当前里程-上次保养里程) /(当前日期-上次保养日期))) +上次保养日期
        //(当前里程-上次保养里程)
        Float surplusMile = nowMile - runMile;
        if (surplusMile <= 0) {
            throw new Exception("里程信息有误!!");
        }
        //平均里程
        //当前日期 -销售日期
        Integer days = DateUtils.dateDifference(nowDate, balanceDate);
        Float avgMile = surplusMile / days;
        //剩下里程除去平均里程 需要用多久跑完
        Float surplusHours = (maintainMile / avgMile) * 24;
        Long nextMaintainTime = DateUtils.addHourLongTime(balanceDate, +surplusHours.intValue());
        String tpl = "%s的车，车主[%s],%s为常保，上次保养时间%s.";
        if (nextMaintainTime > sixMonthDate) {
            nextMaintainTime = sixMonthDate;
            code = "db_mby";
            tpl += "[目标月]";
        }
        String plateNum="";
        if (paramMap.get("plateNum") == null) {
            String vin = String.valueOf(paramMap.get("vin"));
            plateNum = vin.substring(vin.length() - 6, vin.length());
            paramMap.put("plateNum", plateNum);
        }
        tpl = String.format(tpl,plateNum, StringUtil.formatNull(paramMap.get("ownerName")), DateUtils.formatLongTime(nextMaintainTime, Constant.YYYYMMDD),
                StringUtil.formatNull(paramMap.get("balanceTime")));
        return this.saveTask(paramMap, nextMaintainTime, tpl, code, uid, flag);
    }

    /**
     * 生成任务实休
     *
     * @param mTmp
     * @param byTime
     * @param content
     * @param code
     * @param uid
     * @return
     * @throws Exception
     */
    private TCrmTaskReal saveTask(Map<String, Object> mTmp, long byTime, String content,
                                  String code, String uid, boolean flag) throws Exception {
        TCrmTaskReal task = new TCrmTaskReal();
        task.setVIN(mTmp.get("vin").toString());
        task.setCarId(mTmp.get("carId").toString());

        task.setPlateNum(StringUtil.formatEmpty(mTmp.get("plateNum")));
        task.setCompanyId(TokenUtil.getCompanyId(uid));
        task.setSaId(uid);
        task.setLinkman(StringUtil.formatEmpty(mTmp.get("ownerName")));
        if (mTmp.get("ownerTel") != null) {
            task.setLinkphone(StringUtil.formatEmpty(mTmp.get("ownerTel")));
        }
        Long expectDate = null;

        Date newDate = new Date();
        long l = newDate.getTime();

        long ll = DateUtils.addDayLongTime(newDate.getTime(),+7);
        System.out.println(ll);

        if(byTime> DateUtils.addDayLongTime(newDate.getTime(),+7)){ // 未过期
            expectDate = DateUtils.addDayLongTime(byTime, -7); // 显示 -7 天后的时间
        }
        else {//已过期
            expectDate = byTime; // 显示预期时间
        }

       /* if (flag) {

        } else {

        }*/
        task.setExpectDate(DateUtils.formatLongTime(expectDate, Constant.YYYYMMDD));
        task.setStatus("0");
        task.setIsBack("0");
        task.setTypePCode("by");
        task.setTypeCode(code);
        task.setContent(content);
        task.setCreateTime(new Date().getTime());
        task.setCreateUser(uid);
        return task;
    }


    /**
     * 清空工工单维修类别
     *
     * @param companyId
     * @throws Exception
     */
    @Override
    public void moveWorkorderWxType(String companyId) throws Exception {
        String sql = "update t_crm_car_workorder set wx_type =null where company_id=? ";
        this.taskDao.executeSQL(sql, companyId);
    }

    /**
     * 初始化内容
     *
     * @param companyId
     * @throws Exception
     */
    @Override
    public void executeTask(String companyId) throws Exception {
        //更新车辆工单车辆ID
        System.out.println("更新车辆ID....:" + DateUtils.getTimeStr());
        crmCarWorkorderTaskService.updWorkOrderCaridInfoQuartz();
        System.out.println("更新车辆ID....结束" + DateUtils.getTimeStr());

        //更新车辆工单维修类别
        System.out.println("更新工单维修类别....s：" + DateUtils.getTimeStr());
        crmCarWorkorderTaskService.bulidWorkorderPropertyByCompanyQuqrtz(companyId);
        System.out.println("更新工单维修类别....e：" + DateUtils.getTimeStr());

        //更新车辆工单索赔维修类别
        System.out.println("更新工单索赔类别....s：" + DateUtils.getTimeStr());

        crmCarWorkorderTaskService.bulidWorkorderPropertyBySpCompanyQuartz(companyId);
        System.out.println("更新工单索赔类别....e：" + DateUtils.getTimeStr());

        //更新车辆工单产值
        System.out.println("更新工单产值....s：" + DateUtils.getTimeStr());

        crmCarWorkorderTaskService.updWorkOrderAmountInfoQuartz();
        System.out.println("更新工单产值....e：" + DateUtils.getTimeStr());

        //根据工单生成保养工单
        System.out.println("生成保养工单....s：" + DateUtils.getTimeStr());
        crmCarMaintainMileTaskService.createCarMaintainMileQuartz();
        System.out.println("生成保养工单....e：" + DateUtils.getTimeStr());

        //更新车辆行驶里程
        System.out.println("生成行驶里程....s：" + DateUtils.getTimeStr());
        carBaseCountService.updateRunMileQuartz();
        System.out.println("生成行驶里程....e：" + DateUtils.getTimeStr());

        //刷新续保合同结束时间
        System.out.println("更新续保....s：" + DateUtils.getTimeStr());

        crmTimeTaskService.updInsuranceEndDateQuartz();
        System.out.println("更新续保结束....s：" + DateUtils.getTimeStr());

        //根据销售数据
        System.out.println("更新续销售....s：" + DateUtils.getTimeStr());
        crmTimeTaskService.updFromCompanyQuartz();
        System.out.println("更新销售....e：" + DateUtils.getTimeStr());

        //更新延保平均保养里程
        System.out.println("更新延保....s：" + DateUtils.getTimeStr());

        crmTimeTaskService.updExsuranceMaintainAvgMile();
        System.out.println("更新延保....e：" + DateUtils.getTimeStr());

        //生成基盘信息
        System.out.println("生成基盘....s：" + DateUtils.getTimeStr());

        carBaseCountService.countBaseCarQuartz();
        //基盘流失
        carBaseCountService.countLostCarQuartz();
        //计算车辆车龄
        System.out.println("更新车龄...s：" + DateUtils.getTimeStr());

        carBaseCountService.countCarAgeQuartz();
        System.out.println("延保记录....s：" + DateUtils.getTimeStr());

        //刷新延保记录车辆ID及车型
        carBaseCountService.updateExCarSeriesQuartz();
        //延保类型根据类型中文写入类型ID
        System.out.println("更新延保类型....s：" + DateUtils.getTimeStr());

        carBaseCountService.updateExCarTypeQuartz();
        //刷新续保记录车辆ID及车型、联系人电话
        System.out.println("更新续只....s：" + DateUtils.getTimeStr());

        carBaseCountService.updateInCarInfoQuartz();
        //刷新延保起始里程
        System.out.println("更新延保里程....s：" + DateUtils.getTimeStr());

        carBaseCountService.updateExCarMileQuartz();
        //计算车辆行驶里程，更新车辆上次维修时间
        System.out.println("更新行驶....s：" + DateUtils.getTimeStr());

        carBaseCountService.updateRunMileQuartz();
        //刷新续保类型
        System.out.println("更新续保类型....s：" + DateUtils.getTimeStr());

        carBaseCountService.updateInTypeQuartz();
    }
}
